package org.grow.actor.controller;

import org.grow.actor.dao.PurchaseBillMapper;
import org.grow.actor.dao.PurchaseItemMapper;
import org.grow.actor.domain.BillState;
import org.grow.actor.domain.PurchaseBill;
import org.grow.actor.domain.PurchaseItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: xwg
 * @CreateDate: 2023/8/19
 */

@RestController
@RequestMapping("/purchase")
public class PurchaseController {
    @Autowired
    private PurchaseBillMapper purchaseBillMapper;
    @Autowired
    private PurchaseItemMapper purchaseItemMapper;

    @PostMapping("/insert")
    public PurchaseBill insert(@RequestBody PurchaseBill purchaseBill) {
//      purchaseBill.getSupplier()
//      purchaseBill.getOrderDate()
//      purchaseBill.getReceiveDate()
        PurchaseBill pb = new PurchaseBill();
        pb.setSupplier(purchaseBill.getSupplier());
        pb.setOrderDate(purchaseBill.getOrderDate());
        pb.setReceiveDate(purchaseBill.getReceiveDate());

//      设置主表信息
        pb.setBillState(BillState.toSubmit);
        String id = "PB" + System.currentTimeMillis();
        pb.setBillId(id);
        pb.setApplier("zhangsan");
//      ruoyi 获取当前登录人
//    SecurityUtils.getUsername();
        pb.setUpdateTime(LocalDateTime.now());

//   设置子表信息
        BigDecimal amount = new BigDecimal(0);
        List<PurchaseItem> items = purchaseBill.getItems();
        for (PurchaseItem item : items) {
            item.setItemId(0);
            item.setBillFk(id);
            amount = amount.add(item.getPrice().multiply(new BigDecimal(item.getQuantity())));
        }
        System.out.println("后端计算总金额 " + amount.doubleValue());
        pb.setAmount(amount);
        pb.setItems(items);

        purchaseBillMapper.insert(pb);
//        可以书写一个批量新增的接口提高性能
        for (PurchaseItem item : items) {
            purchaseItemMapper.insert(item);
        }
        return pb;


    }


}
